<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { getToken } from '@/utils/auth'
import { getODData } from '@/api/charts'
import { format2Date } from '@/utils'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      listQuery: {
        token: undefined,
        date: undefined
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.listQuery.token = getToken()
      this.listQuery.date = format2Date(new Date(), 'yyyy-MM')
      getODData(this.listQuery).then(response => {
        const data = response.data.map(function(item) {
          return [item[1], item[0], item[2] || '-']
        })
        this.chart.setOption({
          title: {
            text: 'od站点分析',
            left: 'center'
          },
          tooltip: {
            position: 'top'
          },
          grid: {
            height: '50%',
            top: '10%'
          },
          xAxis: {
            type: 'category',
            name: '站点',
            splitArea: {
              show: true
            }
          },
          yAxis: {
            type: 'category',
            name: '站点',
            splitArea: {
              show: true
            }
          },
          visualMap: {
            min: 0,
            max: 10,
            calculable: true,
            orient: 'horizontal',
            left: 'center',
            bottom: '15%'
          },
          series: [{
            name: 'Punch Card',
            type: 'heatmap',
            data: data,
            label: {
              show: true
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        })
      })
    }
  }
}
</script>
